<?php

class IndexController extends CController {

    public function actionIndex() {
        $redirect = array('dashboard/index');
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
            $email = trim($_POST['email']);
            $password = trim($_POST['password']);
            $messages = array();
            if (empty($email)) {
                $messages[] = 'Please input email';
            }
            if (empty($password)) {
                $messages[] = 'Please input password';
            }
            if (!empty($email) && !empty($password)) {
                $condition = new CDbCriteria();
                $condition->condition = 'email = :email AND password = :password AND status = 1';
                $condition->params = array(':email' => $email, ':password' => md5($password));
                $condition->limit = 1;
                $user = User::model()->find($condition);
                if (!empty($user)) {
                    Yii::app()->session['user'] = $user->attributes;
                    $rememberme = intval($_POST['rememberme']);
                    if ($rememberme == 1) {
                        $info = array('email' => $email, 'password' => $password);

                        $cookie_value = serialize($info);
                        $cookie = new CHttpCookie('login_memberme', $cookie_value);
                        //de thoi gian song trong 30 ngay
                        $cookie->expire = time() + 60 * 60 * 24 * 30;
                        Yii::app()->request->cookies['login_memberme'] = $cookie;
                    } elseif (isset(Yii::app()->request->cookies['login_memberme'])) {
                        unset(Yii::app()->request->cookies['login_memberme']);
                    }
                    $this->redirect($redirect);
                } else {
                    $messages[] = 'Incorrect username or password.';
                }
            }
            if (!empty($messages)) {
                $str = '';
                foreach ($messages as $msg) {
                    $str .= '<p>' . $msg . '</p>';
                    Yii::app()->session['msg'] = $str;
                }
            }
        } else {
            $user = Yii::app()->session['user'];
            if (!empty($user)) {
                $this->redirect($redirect);
            }
        }
        $this->render('index');
    }

    public function actionLogout() {
        $user = Yii::app()->session['user'];
        if (!empty($user)) {
            unset(Yii::app()->session['user']);
            Yii::app()->session->clear();
        }
        $this->redirect(array('index/index'));
    }

    public function actionAccessDefine() {
        $this->render('access_define');
    }

}